<?php 
namespace app\wework\model\user\send;
use think\facade\Db;
use think\facade\Session;
use think\facade\Log;
use app\wework\model\QyWechatApi;

/**
* 客户群发
**/
class MassSendModel {
	static public $wid;

	/**
	 * 客户群发列表
	 * @param page 页码
	 * @param times 发送时间
	 * @return
 	*/
	static public function getList($page,$size,$times){
		$wid = Session::get('wid');
 		$where["wid"] = $wid;
		$res = Db::table('kt_wework_customermsg')
					->where($where)
					->page($page,$size)
                    ->json(["staffer","content","groups","exclude_tags","tags","adjunct_data"])
                    ->field("id,staffer,content,groups,exclude_tags,tags,adjunct_data,send_time,send_status,ctime,update_time")
                    ->order("ctime DESC")
					->filter(function($data){
                        $data["alert_status"] = 0;
                        $data["size"] = count($data["adjunct_data"]);
                        $data["staffer"] = array_column(Db::table("kt_wework_staff")->where(["id"=>$data["staffer"]])->field("name")->select()->toArray(),"name");
                        $data["groups"] = array_column(Db::table("kt_wework_group")->where(["chat_id"=>$data["groups"]])->field("name")->select()->toArray(),"name");
                        $data["tags"] = array_column(Db::table("kt_wework_tag")->where(["tag_id"=>$data["tags"]])->field("tag_name")->select()->toArray(),"tag_name");
                        $data["exclude_tags"] = array_column(Db::table("kt_wework_tag")->where(["tag_id"=>$data["exclude_tags"]])->field("tag_name")->select()->toArray(),"tag_name");
                        $data["detail"] = self::getData($data["id"]); //发送结果 已发 未发等等
                        if($data["detail"]["send_staff"] >= 1) $data["alert_status"] = 1;
						return $data;
					});
		    if($times) $res = $res->whereBetweenTime('send_time', $times[0], $times[1]);
			$data['count'] = $res->count();
			$data['item'] = $res->select()->toArray();
			$data['page'] = $page;
			$data['size'] = $size;
		return $data;
	}

	/**
	 * 客户群发群发结果入库
	 * @param staff_id 所属客服id
	 * @param pid 所属群发id
	 * @param fail_list 执行失败的userid列表
	 * @param msgid 群发id
	 * @param send_status 发送状态
     * @param send_size 发送人数
	 * @return
 	*/
	static public function addMsgid($staff_id,$pid,$fail_list=NULL,$msgid=NULL,$status,$send_size=0,$wid=NULL){
		$wid = Session::get('wid')?:$wid;
 		$data["wid"] = $wid;
 		$data["staff_id"] = $staff_id;
 		$data["fail_list"] = json_encode($fail_list,320);
 		$data["pid"] = $pid;
 		$data["msgid"] = $msgid;
 		// $data["send_status"] = $send_status;
        $data["send_size"] = $send_size;
        $data["status"] = $status;
 		$data["ctime"] = date("Y-m-d H:i:s",time());
 		$res = Db::table('kt_wework_customermsgid')->insertGetId($data);
	}

	/**
	 * 创建客户群发
	 * @param customer_gender 性别
	 * @param groups 群聊
	 * @param tags 标签组
	 * @param exclude_tags 隔离标签组
	 * @param times 开始结束时间
	 * @param staffer 员工数组
	 * @param repetition_status 去重是否开启
	 * @param customer_status 类型 是否全部客户
	 * @param content 文本数据
	 * @param adjunct_data 附件
	 * @param send_status 是否立即发送
	 * @param send_time 发送时间
	 * @return
 	*/
	static public function addMsg($staffer,$customer_status,$customer_gender=NULL,$groups=NULL,$tags=NULL,$exclude_tags=NULL,$times=NULL,$repetition_status,$content,$adjunct_data,$send_status,$send_time=NULL,$all=NULL){
		$wid = Session::get('wid');
 		$data["wid"] = $wid;
 		$data["send_status"] = $send_status;
 		$data["customer_status"] = $customer_status;
        $data["send_time"] = date("Y-m-d H:i:s");
        if($send_status == 2){
            $data["send_time"] = $send_time;
        }
        if($customer_status == 2){
            $data["customer_gender"] = $customer_gender;
            if($times)$data["start_time"] = $times[0];
            if($times)$data["end_time"] = $times[1];
        }
 		$data["repetition_status"] = $repetition_status;
 		$data["exclude_tags"] = json_encode($exclude_tags,320);
 		$data["tags"] = json_encode($tags,320);
 		$data["groups"] = json_encode($groups,320);
 		$data["staffer"] = json_encode($staffer,320);
 		$data["content"] = json_encode($content,320);
 		$data["adjunct_data"] = json_encode($adjunct_data,320);
 		$data["ctime"] = date("Y-m-d H:i:s",time());

 		$res = Db::table('kt_wework_customermsg')->insertGetId($data);
 		return $res;
	}
	/**
	 * 获取发送成员的列表
	 * @return staffer 员工数组
	 * @return repetition_status 去重是否开启
 	*/
	static	public function externalLists($staffer,$repetition_status=NULL,$wid=NULL){
		$wid = Session::get('wid')?:$wid;
 		$where["c.wid"] = $wid;
 		$where["c.status"] = 0;
 		$where["c.staff_id"] = $staffer;
 		$res = Db::table("kt_wework_customer")
					->alias('c')
					->join(['kt_wework_staff'=>'f'],'c.staff_id = f.id')
 					->where($where);
		if($repetition_status == 1) $res = $res->group('external_userid');
 					$res = $res->order("staff_id DESC")
 					->field("c.external_userid,c.staff_id,f.userid")
					->select()
					->toArray();
		return $res;
	}
	/**
	 * 获取发送成员的列表
	 * @return customer_gender 性别
	 * @return groups 群聊
	 * @return tags 标签组
	 * @return exclude_tags 隔离标签组
	 * @return times 开始结束时间
	 * @return staffer 员工数组
	 * @return repetition_status 去重是否开启
 	*/
	static	public function externalList($staffer,$customer_gender,$groups,$tags,$exclude_tags,$times,$repetition_status=NULL,$wid=NULL){
 		$wid = Session::get('wid')?:$wid;
		$res = Db::table("kt_wework_customer")
						->alias('c')
						->join(['kt_wework_staff'=>'f'],'c.staff_id = f.id')
						->join(['kt_wework_group_member'=>'m'],'c.external_userid = m.userid');
        if($tags){
            foreach ($tags as $value){
                $where = [];
                $where[0] = ["c.wid","=",$wid];
                $where[0] = ["c.staff_id","in",$staffer];
                $where[0] = ["c.status","=",0];
                if($groups) $where[0] = ["m.chat_id","in",$groups];
                if($customer_gender == 2) $where[0] = ["c.gender","=",1];
                if($customer_gender == 3) $where[0] = ["c.gender","=",2];
                if($customer_gender == 4) $where[0] = ["c.gender","=",0];
                $where[0] = ["c.tags","like","%{$value}%"];
                $res = $res->whereOr($where);
            }
        }else{
            $where[] = ["c.wid","=",$wid];
            $where[] = ["c.staff_id","in",$staffer];
            $where[] = ["c.status","=",0];
            if($groups) $where[] = ["m.chat_id","in",$groups];
            if($customer_gender == 2) $where[] = ["c.gender","=",1];
            if($customer_gender == 3) $where[] = ["c.gender","=",2];
            if($customer_gender == 4) $where[] = ["c.gender","=",0];
            $res = $res->where($where);
        }
		if($times) $res = $res->whereBetweenTime('c.createtime', strtotime($times[0]), strtotime($times[1]));
		if($exclude_tags) for ($i=0;$i<count($exclude_tags);$i+=1){$res = $res->whereNotLike('c.tags','%'.$exclude_tags[$i].'%');}
		if($repetition_status == 1) $res = $res->group('external_userid');
					$res = $res->field("c.external_userid,c.staff_id,f.userid")
					->order("staff_id DESC")
					->select()
					->toArray();
		return $res;
	}

    static public function getAlls(){
        $wid = Session::get('wid');
        $where["wid"] = $wid;
        $where["is_del"] = 0;
        $where["status"] = 1;
        $res = Db::table("kt_wework_staff")
                    ->where($where)
                    ->column("id");

        return $res;
    }

	/**
	 * 获取全部成员id
	 * @return 
	 */
 	static public function getAll($staffer=NULL,$wid=NULL){
 		$wid = Session::get('wid')?:$wid;
 		$where["wid"] = $wid;
        if($staffer)$where["id"] = $staffer;
 		$res = Db::table("kt_wework_staff")
 					->where($where)
 					->field("id,userid")
 					->filter(function($data){
 						$data["detail_count"] = Db::table("kt_wework_customer")->where(["staff_id"=>$data["id"],"status"=>0])->count();
 						return $data;
 					})
 					->select()
 					->toArray();
		return $res;
	}

	//组装 换迎语附件 数据
    static public function assembleOther($otherData,$wid){
        $data = [];
        foreach ($otherData as $other) {
            switch ($other['type']) {
                case '1':
                    $data[] = [
                        'msgtype'=>'image',
                        'image'=>[
                            'media_id' => QyWechatApi::mediaUpload($wid,$other['url'],'image')['media_id'],
                        ]
                    ];
                    break;
                case '2':
                    $data[] = [
                        'msgtype'=>'link',
                        'link'=>[
                            'title' => $other['link_title'],
                            'picurl' => $other['link_picurl'],
                            'desc' => $other['link_desc'],
                            'url' => $other['link_url'],
                        ]
                    ];
                    break;
                case '3':
                    $data[] = [
                        'msgtype'=>'miniprogram',
                        'miniprogram'=>[
                            'title' => $other['miniprogram_title'],
                            'pic_media_id' => QyWechatApi::mediaUpload($wid,$other['miniprogram_imgurl'],'image')['media_id'],
                            'appid' => $other['miniprogram_appid'],
                            'page' => $other['miniprogram_page'],
                        ]
                    ];
                    break;
            }
        }
        return $data;
    }

    /*
    * 获取本条数据
    */
    static public function getMsg($id){
    	$res = Db::table('kt_wework_customermsg')
                ->where(["id"=>$id])
                ->json(["staffer","content","groups","adjunct_data"])
                ->field("staffer,content,groups,adjunct_data,send_status,send_time,ctime,update_time")
				->filter(function($data){
                    $data["alert_status"] = 0;
                    $data["groups"] = array_column(Db::table("kt_wework_group")->where(["chat_id"=>$data["groups"]])->field("name")->select()->toArray(),"name");
					$data["staffer"] = array_column(Db::table("kt_wework_staff")->where(["id"=>$data["staffer"]])->field("name")->select()->toArray(),"name");
					return $data;
				})->find();

 		return $res;
    }

    /**
    * 获取所有的未发送的成员列表
    */
    static public function getDetailList($id){
        $wid = Session::get('wid');
        $res =  Db::table("kt_wework_customermsgid")->where(["wid"=>$wid,"pid"=>$id,"status"=>2])->where("send_size","<>",0)->field("staff_id,send_size")->select()->toArray();
        return $res;
    }

    /*
    * 获取详情中详细数据
    * send_staff 已发送成员数量
    * delivery_customer 送达用户数量
    * unsent_staff 未发送成员数量
    * unsent_customer 未送达客户数量
    * limit_customer 客户接收已达上限数量
    * not_customer 因不是好友发送失败数量
    */
    static public function getData($id){
 		$wid = Session::get('wid');
 		$send_staff = Db::table("kt_wework_customermsgid")->where(["wid"=>$wid,"pid"=>$id,"status"=>1])->count();
 		$delivery_customer = Db::table("kt_wework_customermsg_detail")->where(["wid"=>$wid,"pid"=>$id,"status"=>1])->count();
        $unsent_staff = Db::table("kt_wework_customermsgid")->where(["wid"=>$wid,"pid"=>$id,"status"=>2])->count();
        $unsent_customer =  Db::table("kt_wework_customermsg_detail")->where(["wid"=>$wid,"pid"=>$id,"status"=>0])->count();
        $limit_customer =  Db::table("kt_wework_customermsg_detail")->where(["wid"=>$wid,"pid"=>$id,"status"=>3])->count();
        $not_customer =  Db::table("kt_wework_customermsg_detail")->where(["wid"=>$wid,"pid"=>$id,"status"=>2])->count();
        $data["send_staff"] = $send_staff;
        $data["delivery_customer"] = $delivery_customer;
        $data["unsent_staff"] = $unsent_staff;
        $data["unsent_customer"] = $unsent_customer;
        $data["limit_customer"] = $limit_customer;
        $data["not_customer"] = $not_customer;
        return $data;
    }

    /**
    * 获取员工userid
    */
    static public function getUser($id){
    	$res = Db::table('kt_wework_staff')->field("userid")->find($id);
    	return $res;
    }

    /**
    * 同步记录入库
    */
    static public function addDetail($send_list,$wid,$msg){
        $staff_id = $msg["staff_id"];
        $data["wid"] = $wid;
        $data["pid"] = $msg["pid"];
        $data["msg_id"] = $msg["id"];
        $data["staff_id"] = $staff_id;
    	foreach($send_list as $send){
            $detail = Db::table('kt_wework_customermsg_detail')->where(["wid"=>$wid,"external_userid"=>$send["external_userid"],"msg_id"=>$msg["id"],"staff_id"=>$staff_id])->find();
    		$data["external_userid"] = $send["external_userid"];
    		if(isset($send["status"]))$data["status"] = $send["status"];
            if(isset($send["send_time"]))$data["send_time"] = date("Y-m-d H:i:s",$send["send_time"]);
            if($detail)Db::table('kt_wework_customermsg_detail')->where(["id"=>$detail["id"]])->save($data);
            if(!$detail)Db::table('kt_wework_customermsg_detail')->insertGetId($data);
        }

		return "1";
    	
    }

    //修改状态，定时任务的
    static public function msgSet($msg,$size){
    	$count = Db::table('kt_wework_customermsg_detail')->where(["msg_id"=>$msg["id"]])->where("status","<>",0)->count();
    	if($count)$res = Db::table("kt_wework_customermsgid")->where(["id"=>$msg["id"]])->update(["status"=>1]);

	    return '1';
    }

    //修改状态
    static public function msgUpd($id){
    	$res = Db::table("kt_wework_customermsg")->where(["id"=>$id])->update(["send_status"=>1]);
	    return $res;
    }

    /**
    * 客户群发详情
    * id 群发主键id
    */
    static public function detailUser($page,$size,$id,$type,$name=NULL,$wid=NULL){
 		$wid = Session::get('wid')?:$wid;
 		$where["m.wid"] = $wid;
 		$where["m.pid"] = $id;
 			if($type == 2) $where["m.status"] = 1;
 			if($type == 3) $where["m.status"] = 2;
            if($type == 4) $where["m.status"] = 3;
    		$res = Db::table("kt_wework_customermsgid")
					->alias('m')
					->leftjoin(['kt_wework_staff'=>'f'],'m.staff_id = f.id')
    				->where($where);
            if($name)$res = $res->whereLike('f.name','%'.$name.'%');
            $data["count"] = $res->count();
            $data["page"] = $page;
            $data["size"] = $size;
            $data["item"] = $res->page($page,$size)
    				->field("m.id,m.msgid,f.name,f.avatar,m.send_size,m.status")
    				->select()
    				->toArray();
	    return $data;
    }

    /**
    * 详情获取客户信息
    */
     static public function detailCustomer($page,$size,$id,$type,$name=NULL,$wid=NULL){
        $wid = Session::get('wid')?:$wid;
        $where["d.wid"] = $wid;
        $where["d.pid"] = $id;
        if($type == 1)$where["d.status"] = 1;
        if($type == 2)$where["d.status"] = 0;
        if($type == 4)$where["d.status"] = 2;
        if($type == 3)$where["d.status"] = 3;
        $customerList = Db::table("kt_wework_customermsg_detail")
                            ->alias("d")
                            ->join(['kt_wework_staff'=>'f'],'d.staff_id = f.id')
                            ->join(['kt_wework_customer'=>'c'],'d.external_userid = c.external_userid and d.staff_id = c.staff_id')
                            ->where($where);
        if($name)$customerList = $customerList->whereLike('c.name','%'.$name.'%');
        $data['count'] = $customerList->count();
        $data['item'] = $customerList->page($page,$size)
                            ->field("d.status,c.name,c.avatar,f.name as staff_name")
                            ->select()
                            ->toArray();
        $data['page'] = $page;
        $data['size'] = $size;
        return $data;
    }

    /*
    * 获取当前员工未发送的成员数量
    */
    static  public  function getStaffSize($staff_id,$id){
        $wid = Session::get('wid');
        $res = Db::table("kt_wework_customermsgid")->find(["wid"=>$wid,"staff_id"=>$staff_id,"pid"=>$id])->field("send_size");
        return $res;
    }


    /**
    * 获取部门下员工列表
    * 
    */
    static public function departmentAll($department,$staffer){
        $wid = Session::get('wid');
        $where["wid"] = $wid;
        $where["id"] = $department;
        $res = Db::table("kt_wework_department")
                        ->where($where)
                        ->field("department_id,department_name")
                        ->select()
                        ->toArray();
        $data = Db::table("kt_wework_staff");
        foreach($res as $value){
            $where = [];     
            $where[0] = ["wid","=",$wid];
            $where[0] = ["department","like","%{$value['department_id']}%"];
            $where[0] = ["department_name","like","%\"{$value['department_name']}\"%"];
            $data = $data->whereOr($where);
        }
        $data = $data->field("id")
                        ->select()
                        ->toArray();
        return array_unique(array_merge(array_column($data,"id"),$staffer));
    }
}